import { useNotification } from '@web3uikit/core'
import Image from 'next/image'
import React, { useEffect, useState } from 'react'
import { useWeb3Contract } from 'react-moralis'
import { useMoralis } from 'react-moralis'
import styles from '../styles/Home.module.css'
const contractAddress = require('../constant/networkUpdateHook.json')
import { ethers } from 'ethers'
import { Form } from '@web3uikit/core'
import { Button } from '@web3uikit/core'
import nftAbi from '../constant/BasicNFT.json'
import NFTSHOPAbi from '../constant/NFTSHOP.json'

export default function Home() {
  const { chainId, account, isWeb3Enabled } = useMoralis()
  const chainString = chainId ? parseInt(chainId).toString() : '31337'
  const NFTSHOPAddress = contractAddress[chainString].NFTSHOP[0]
  const dispatch = useNotification()
  const [proceeds, setProceeds] = useState('0')

  // @ts-ignore
  const { runContractFunction } = useWeb3Contract()

  async function approveAndList(data) {
    console.log('Approving...')
    const nftAddress = data.data[0].inputResult
    const tokenId = data.data[1].inputResult
    const price = ethers.utils.parseUnits(data.data[2].inputResult, 'ether').toString()

    const approveOptions = {
      abi: nftAbi,
      contractAddress: nftAddress,
      functionName: 'approve',
      params: {
        to: NFTSHOPAddress,
        tokenId: tokenId
      }
    }

    await runContractFunction({
      params: approveOptions,
      onSuccess: () => handleApproveSuccess(nftAddress, tokenId, price),
      onError: error => {
        console.log(error)
      }
    })
  }

  async function handleApproveSuccess(nftAddress, tokenId, price) {
    console.log('Ok! Now time to list')
    const listOptions = {
      abi: NFTSHOPAbi,
      contractAddress: NFTSHOPAddress,
      functionName: 'listItem',
      params: {
        nftAddress: nftAddress,
        tokenId: tokenId,
        price: price
      }
    }

    await runContractFunction({
      params: listOptions,
      onSuccess: handleListSuccess,
      onError: error => console.log(error)
    })
  }

  async function handleListSuccess(tx) {
    await tx.wait(1)
    dispatch({
      type: 'success',
      message: 'NFT listing',
      title: 'NFT listed',
      position: 'topR'
    })
  }

  const handleWithdrawSuccess = async tx => {
    await tx.wait(1)
    dispatch({
      type: 'success',
      message: 'Withdrawing proceeds',
      position: 'topR'
    })
  }

  async function setupUI() {
    const returnedProceeds = await runContractFunction({
      params: {
        abi: NFTSHOPAbi,
        contractAddress: NFTSHOPAddress,
        functionName: 'getSellerProceeds',
        params: {
          seller: account
        }
      },
      onError: error => console.log(error)
    })
    if (returnedProceeds) {
      // @ts-ignore
      setProceeds(returnedProceeds.toString())
    }
  }

  useEffect(() => {
    if (isWeb3Enabled) {
      setupUI()
    }
  }, [proceeds, account, isWeb3Enabled, chainId])

  return (
    <div className={styles.container}>
      <Form
        onSubmit={approveAndList}
        data={[
          {
            name: 'NFT Address',
            type: 'text',
            inputWidth: '50%',
            value: '',
            key: 'nftAddress'
          },
          {
            name: 'Token ID',
            type: 'number',
            value: '',
            key: 'tokenId'
          },
          {
            name: 'Price (in ETH)',
            type: 'number',
            value: '',
            key: 'price'
          }
        ]}
        title="Sell your NFT!"
        id="Main Form"
      />
      <div>Withdraw {proceeds} proceeds</div>
      {proceeds != '0' ? (
        <Button
          onClick={() => {
            runContractFunction({
              params: {
                abi: NFTSHOPAbi,
                contractAddress: NFTSHOPAddress,
                functionName: 'withdrawProceeds',
                params: {}
              },
              onError: error => console.log(error),
              onSuccess: handleWithdrawSuccess
            })
          }}
          text="Withdraw"
          type="button"
        />
      ) : (
        <div>No proceeds detected</div>
      )}

      <footer className={styles.footer}>
        <a href="http://fengpangzi.top:9999" target="_blank" rel="noopener noreferrer">
          Powered by{'  hanxin'}
          <span className={styles.Logo}>
            <Image src="/happy.svg" alt=" Logo" width={20} height={16} />
          </span>
        </a>
      </footer>
    </div>
  )
}
